package com.etc.library.controller;

import com.etc.library.pojo.Record;
import com.etc.library.pojo.User;
import com.etc.library.service.UserService;
import com.etc.library.util.JWTUtil;
import com.etc.library.util.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/logon")
    public ResultBody logon(@RequestBody User ur){
        User user = userService.logon(ur.getUsername(), ur.getPassword());
        if(user == null){
            return ResultBody.error("登录失败，用户名不存在或者密码不匹配");
        }
        String token = JWTUtil.generateToken(user.getUserId(),user.getURole());
        Map<String,Object> result = new HashMap<>();
        result.put("token",token);
        result.put("username",user.getRealName());
        if (user.getURole() == 0){
            result.put("path","/home");
        }else{
            result.put("path","/index");
        }
        return ResultBody.success("登录成功",result);
    }


    @PostMapping("/register")
    public ResultBody register(@RequestBody User user){
        user.setRealName(user.getUsername());
        if(userService.register(user))
            return ResultBody.success();
        return ResultBody.error();
    }

}
